package com.haieros.www.purerunshowsystem;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.haieros.www.purerunshowsystem.utils.SDUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.open.androidtvwidget.bridge.EffectNoDrawBridge;
import com.open.androidtvwidget.view.GridViewTV;
import com.open.androidtvwidget.view.MainUpView;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2017/11/22.
 */

public class GridViewLocalVideoActivity extends Activity {
    private List<VideoModel> mDatas;
    private ArrayList<String> mListStrUrl = new ArrayList<>();
    Uri uri;
    private MainUpView mainUpView1;
    private View mOldView;
    private GridViewTV gridView;
    private GridViewLocalVideoActivity.GridViewAdapter mAdapter;
    private int mSavePos = -1;
    private int mCount = 50;
    private List<VideoModel> videoinfos = new ArrayList<VideoModel>(); //视频文件集合
    private ListView lv; //listview
    private DisplayImageOptions options;
    protected ImageLoader imageLoader = ImageLoader.getInstance();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo_localgridview_layout);
        //初始化
        init();
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                /**
                 * 这里注意要加判断是否为NULL.
                 * 因为在重新加载数据以后会出问题.
                 */
                if (view != null) {
                    mainUpView1.setFocusView(view, mOldView, 1.1f);
                }
                mOldView = view;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mFindhandler.removeCallbacksAndMessages(null);
                handler.removeCallbacksAndMessages(null);
                mSavePos = position; // 保存原来的位置(
                //initGridViewData(new Random().nextInt(3));
                mFindhandler.sendMessageDelayed(mFindhandler.obtainMessage(), 111);
                Intent intent=new Intent(getApplicationContext(),VideoViewDemoActivity.class);
                intent.putExtra("data",mDatas.get(position));
                intent.putExtra("position",position);
                intent.putStringArrayListExtra("paths",mListStrUrl);
                startActivity(intent);
            }
        });
        //initGridViewData(new Random().nextInt(3));
        mFirstHandler.sendMessageDelayed(mFirstHandler.obtainMessage(), 188);
    }
    //初始化
    @SuppressWarnings("deprecation")
    private void init() {

        gridView = (GridViewTV) findViewById(R.id.gridView);
        mainUpView1 = (MainUpView) findViewById(R.id.mainUpView1);
        // 建议使用 NoDraw.
        mainUpView1.setEffectBridge(new EffectNoDrawBridge());
        EffectNoDrawBridge bridget = (EffectNoDrawBridge) mainUpView1.getEffectBridge();
        bridget.setTranDurAnimTime(200);
        // 设置移动边框的图片.
        options = new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.ic_launcher)
                .showImageForEmptyUri(R.drawable.ic_launcher)
                .showImageOnFail(R.drawable.ic_launcher)
                .cacheInMemory(true).cacheOnDisk(true)
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                .bitmapConfig(Bitmap.Config.RGB_565).build();
        ScannerAnsyTask ansyTask=new ScannerAnsyTask();
        ansyTask.execute();
    }

    // 延时请求初始位置的item.
    Handler mFirstHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //mainUpView1.setFocusView(convertView,null, 1.2f);
            gridView.setDefualtSelect(0);
        }
    };

    // 更新数据后还原焦点框.
    Handler mFindhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (mSavePos != -1) {
                gridView.requestFocusFromTouch();
                gridView.setSelection(mSavePos);
            }
        }
    };


    ///// Adapter 类 start start //////////

    class GridViewAdapter extends BaseAdapter {


        private final LayoutInflater mInflater;

        public GridViewAdapter(Context context, List<VideoModel> data) {
            mDatas = data;
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return mDatas.size();
        }

        @Override
        public Object getItem(int position) {
            return mDatas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            GridViewLocalVideoActivity.GridViewAdapter.ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_gridview, parent, false);
                convertView.setTag(new GridViewLocalVideoActivity.GridViewAdapter.ViewHolder(convertView));
            }
//            convertView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Toast.makeText(getApplicationContext(), "GridView Item " + mDatas.get(position).getPath(), Toast.LENGTH_LONG).show();
//                    Log.d("TAG","====="+mDatas.get(position).getPath());
//                }
//            });
            viewHolder = (GridViewLocalVideoActivity.GridViewAdapter.ViewHolder) convertView.getTag();
            bindViewData(position, viewHolder);
            return convertView;
        }

        private void bindViewData(int position, GridViewLocalVideoActivity.GridViewAdapter.ViewHolder viewHolder) {

            String title = mDatas.get(position).getName();
            viewHolder.titleTv.setText(title);
            uri = Uri.fromFile(new File(mDatas.get(position).getPath()));
            imageLoader.displayImage(uri+"",viewHolder.imageVideo,options);

        }

        class ViewHolder {
            View itemView;
            TextView titleTv;
            ImageView imageVideo;
            public ViewHolder(View view) {
                this.itemView = view;
                this.titleTv = (TextView) view.findViewById(R.id.textView);
                this.imageVideo= (ImageView) view.findViewById(R.id.image_video);
            }
        }
    }

    ///// Adapter 类 end end //////////
    //在主线程更新界面
    private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    gridView.setAdapter(mAdapter);
                    break;
            }
            return false;
        }
    });

    /**10M=10485760 b,小于10m的过滤掉
     * 过滤视频文件
     * @param videoInfos
     * @return
     */
    private List<VideoModel> filterVideo(List<VideoModel> videoInfos){
        List<VideoModel> newVideos=new ArrayList<VideoModel>();
        for(VideoModel videoInfo:videoInfos){
            File f=new File(videoInfo.getPath());
            if(f.exists()&&f.isFile()&&f.length()>512){
                newVideos.add(videoInfo);
                Log.i("TGA","文件大小"+f.length());
            }else {
                Log.i("TGA","文件太小或者不存在");
            }
        }
        return newVideos;
    }
    //异步执行
    public class ScannerAnsyTask extends AsyncTask<Void,Integer,List<VideoModel>> {
        private List<VideoModel> videoInfos = new ArrayList<VideoModel>();

        @Override
        protected List<VideoModel> doInBackground(Void... params) {
            videoInfos = SDUtils.getVideoFile(videoInfos,null);
            videoInfos = filterVideo(videoInfos);
            Log.i("tga", "最后的大小" + videoInfos.size());
            return videoInfos;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(List<VideoModel> videoInfos1) {
            super.onPostExecute(videoInfos1);
            for (int i = 0; i < videoInfos1.size(); i++) {
                mListStrUrl.add(videoInfos1.get(i).getPath());
            }

            mAdapter = new GridViewLocalVideoActivity.GridViewAdapter(getApplicationContext(),videoInfos1);
            Message msg = new Message();
            msg.what = 1;
            handler.sendMessage(msg);
        }
    }
    //数据库读取视频文件
    public List<VideoModel> getSDCardVideoFiles(String path) {
        List<VideoModel> list = new ArrayList<VideoModel>();
        ContentResolver cr = getContentResolver();
        String[] projection = new String[] { MediaStore.Video.Media.DATA,MediaStore.Video.Media.TITLE };
        Cursor cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                projection, null, null,
                MediaStore.Video.Media.DEFAULT_SORT_ORDER);
        cursor.moveToFirst();
        int count = cursor.getCount();
        for (int i = 0; i < count; i++) {
            String address = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
            String name = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
            VideoModel model = new VideoModel();
            model.setPath(address);
            model.setName(name);
            list.add(model);
            cursor.moveToNext();
        }
        return list;
    }


    //通过文件路径获取文件的大小,并自动格式化
    public String getVideoLength(String filePath){
        String string = "0B";
        DecimalFormat df = new DecimalFormat();
        File file = new File(filePath);
        long length = file.length();
        if(length==0){ //文件大小为0,直接返回0B
            return string;
        }
        if(length<1024){ //文件小于1KB,单位为 B
            string = df.format((double)length)+"B";
        }else if(length<1048576){//文件小于1M,单	位为 KB
            string = df.format((double)length/1024)+"K";
        }else if(length<1073741824){//文件小于1G,单	位为 MB
            string = df.format((double)length/1048576)+"M";
        }else{
            string = df.format((double)length/1073741824)+"G";
        }
        return string;
    }
}